import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_module/common/base/base_page.dart';
import 'package:flutter_module/common/extensions/cached_network_image_extension.dart';
import 'package:flutter_module/common/utils/object_to_any.dart';
import 'package:flutter_module/common/utils/toast_utils.dart';
import 'package:flutter_module/common/widget/CustomDialog.dart';
import 'package:flutter_module/common/widget/video/video_player_dialog.dart';
import 'package:flutter_module/core/flutter_bridge.dart';
import 'package:flutter_module/model/native_image_options.dart';
import 'package:flutter_module/model/native_media_type.dart';
import 'package:flutter_module/page/base/base_view.dart';
import 'package:flutter_module/page/base/max_input_edit_text_page.dart';
import 'package:flutter_module/style/colors.dart';

/// 合作服务商简介编辑页
class ServiceProviderProfileEditPage extends BaseStateFulWidget {
  final Map<String, dynamic>? params;
  const ServiceProviderProfileEditPage({Key? key, this.params})
      : super(key: key);

  @override
  BaseState<StatefulWidget> buildState() {
    return _ServiceProviderProfileEditPageState();
  }
}

class _ServiceProviderProfileEditPageState
    extends BaseState<ServiceProviderProfileEditPage>
    with BasePage<ServiceProviderProfileEditPage> {
  String get _videoUrl {
    return object2string(widget.params?['videoUrl']);
  }

  String get _videoCoverUrl {
    return object2string(widget.params?['videoImage']);
  }

  String get _companyProfile {
    return object2string(widget.params?['companyProfile']);
  }

  /// 信息是否被修改
  bool get _isModified {
    return _modifiableVideoUrl != _videoUrl ||
        _modifiableCompanyProfile != _companyProfile ||
        _modifiableVideoCoverUrl != _videoCoverUrl;
  }

  late String _modifiableVideoUrl;
  late String _modifiableVideoCoverUrl;
  late String _modifiableCompanyProfile;

  @override
  Widget createView(BuildContext context) {
    print('_ServiceProviderProfileEditPageState.createView');
    return GestureDetector(
      child: Container(
        width: double.infinity,
        color: Colors.white,
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _profileWidget(context),
              _videoWidget(context),
              if (_modifiableVideoUrl.isEmpty &&
                  _modifiableVideoCoverUrl.isEmpty)
                SizedBox(
                  height: 11.0,
                )
              else
                _videoCoverWidget(context)
            ],
          ),
        ),
      ),
      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
    );
  }

  _playVideo() {
    VideoPlayerDialog.show(
      videoUrl: _modifiableVideoUrl,
      videoCover: _modifiableVideoCoverUrl,
    );
  }

  Widget _profileWidget(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 9.0, horizontal: 16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text.rich(
            TextSpan(
                text: '*',
                children: [
                  TextSpan(
                    text: '简介',
                    style: TextStyle(color: ThemeColors.text333),
                  ),
                ],
                style: TextStyle(color: ThemeColors.redEF5D5E)),
            style: TextStyle(
              fontSize: 14.0,
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(
            height: 12.0,
          ),
          MaxInputEditTextPage(
            maxLength: 150,
            content: _modifiableCompanyProfile,
            hintText: '请填写简介',
            showLine: 6,
            onChanged: (value) {
              _modifiableCompanyProfile = value;
            },
          )
        ],
      ),
    );
  }

  Widget _videoWidget(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 9.0, horizontal: 16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '视频',
            style: TextStyle(
              color: ThemeColors.text333,
              fontSize: 14.0,
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(
            height: 10.0,
          ),
          if (_modifiableVideoUrl.isEmpty)
            TextButton(
              style: TextButton.styleFrom(
                padding: EdgeInsets.zero,
                splashFactory: NoSplash.splashFactory,
              ),
              onPressed: () async {
                final url = await FlutterPlatformBridge.getInstance()
                    .selectAndUploadFromPhotos(
                        displayMediaType: NativeMediaType.video);
                if (url.isNotEmpty) {
                  setState(() {
                    _modifiableVideoUrl = url;
                  });
                }
              },
              child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5.0),
                  border: Border.all(
                    color: ThemeColors.grayE5E5E5,
                    width: 0.5,
                  ),
                ),
                padding: EdgeInsets.symmetric(vertical: 11.0, horizontal: 12.0),
                child: Row(
                  children: [
                    Image.asset(
                      'images/service_provider/service_provider_video_icon.png',
                      width: 22.0,
                      height: 16.0,
                    ),
                    SizedBox(
                      width: 7.0,
                    ),
                    Text(
                      '点击上传',
                      style: TextStyle(
                        color: ThemeColors.text888,
                        fontSize: 14.0,
                        fontWeight: FontWeight.w500,
                      ),
                    )
                  ],
                  mainAxisSize: MainAxisSize.min,
                ),
              ),
            )
          else
            AspectRatio(
              aspectRatio: 343.0 / 150.0,
              child: Stack(
                children: [
                  ClipRRect(
                    child: SizedBox.expand(
                      child: YFNetworkImage(
                        resource: _modifiableVideoCoverUrl,
                        placeholderName: ImagePlaceholder.largePlaceholder,
                        fit: BoxFit.cover,
                      ),
                    ),
                    borderRadius: BorderRadius.circular(5.0),
                  ),
                  Center(
                    child: SizedBox(
                      width: 42.0,
                      height: 42.0,
                      child: TextButton(
                        style: TextButton.styleFrom(
                          padding: EdgeInsets.zero,
                          splashFactory: NoSplash.splashFactory,
                        ),
                        onPressed: _playVideo,
                        child: Image.asset(
                          'images/service_provider/video_play_icon.png',
                        ),
                      ),
                    ),
                  ),
                  Align(
                    alignment: Alignment.topRight,
                    child: _deleteButton(() {
                      setState(() {
                        _modifiableVideoUrl = '';
                      });
                    }),
                  )
                ],
              ),
            )
        ],
      ),
    );
  }

  Widget _videoCoverWidget(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 9.0, horizontal: 16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '视频封面',
            style: TextStyle(
              color: ThemeColors.text333,
              fontSize: 14.0,
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(
            height: 10.0,
          ),
          GestureDetector(
            onTap: () async {
              final url = await FlutterPlatformBridge.getInstance()
                  .selectAndUploadFromPhotos(
                imageOptions: NativeImageOptions(
                  directory: 'service/provider',
                  isOss: true,
                  clippingWidth: 16.0,
                  clippingHeight: 9.0,
                ),
              );
              if (url.isNotEmpty) {
                setState(() {
                  _modifiableVideoCoverUrl = url;
                });
              }
            },
            child: SizedBox(
              width: 80.0,
              height: 80.0,
              child: ClipRRect(
                borderRadius: BorderRadius.circular(5.0),
                child: Stack(
                  fit: StackFit.expand,
                  children: [
                    YFNetworkImage(
                      resource: _modifiableVideoCoverUrl,
                      placeholderName: _modifiableVideoCoverUrl.isNotEmpty
                          ? ImagePlaceholder.largePlaceholder
                          : 'images/service_provider/service_provider_add_img.png',
                      fit: BoxFit.cover,
                    ),
                    if (_modifiableVideoCoverUrl.isNotEmpty)
                      Align(
                        child: _deleteButton(() {
                          setState(() {
                            _modifiableVideoCoverUrl = '';
                          });
                        }),
                        alignment: Alignment.topRight,
                      )
                  ],
                ),
              ),
            ),
          ),
          SizedBox(
            height: 20.0,
          ),
        ],
      ),
    );
  }

  Widget _deleteButton(VoidCallback? onPressed) {
    return SizedBox(
      width: 21.0,
      height: 21.0,
      child: TextButton(
        style: TextButton.styleFrom(
          padding: EdgeInsets.zero,
          splashFactory: NoSplash.splashFactory,
        ),
        onPressed: onPressed,
        child: Image.asset(
          'images/service_provider/service_provider_case_delete.png',
        ),
      ),
    );
  }

  saveProfile() {
    if (_modifiableCompanyProfile.isEmpty) {
      ToastUtils().showText('请输入简介');
      return;
    }

    if (_modifiableVideoUrl.isNotEmpty && _modifiableVideoCoverUrl.isEmpty) {
      ToastUtils().showText('请上传封面');
      return;
    }

    Navigator.of(context).pop({
      'videoUrl': _modifiableVideoUrl,
      'videoImage': _modifiableVideoCoverUrl,
      'companyProfile': _modifiableCompanyProfile,
    });
  }

  @override
  getActions() {
    return [
      TextClickView(
        title: '保存',
        rightClick: saveProfile,
      )
    ];
  }

  @override
  String get appBarTitle => '服务商简介';

  @override
  onBack() {
    if (_isModified) {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (_) {
            return CustomDialog(
              content: '信息已修改，确认是否离开？',
              cancelContent: "取消",
              confirmContent: "确定离开",
              confirmCallback: () {
                super.onBack();
              },
            );
          });
    } else {
      super.onBack();
    }
  }

  @override
  void initState() {
    print('_ServiceProviderProfileEditPageState.initState');
    _modifiableVideoUrl = _videoUrl;
    _modifiableCompanyProfile = _companyProfile;
    _modifiableVideoCoverUrl = _videoCoverUrl;
    super.initState();
  }

  @override
  void dispose() {
    print('_ServiceProviderProfileEditPageState.dispose');
    super.dispose();
  }

  @override
  void deactivate() {
    print('_ServiceProviderProfileEditPageState.deactivate');
    super.deactivate();
  }

  @override
  void reassemble() {
    print('_ServiceProviderProfileEditPageState.reassemble');
    super.reassemble();
  }

  @override
  void didUpdateWidget(oldWidget) {
    print('_ServiceProviderProfileEditPageState.didUpdateWidget');
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    print('_ServiceProviderProfileEditPageState.didChangeDependencies');
    super.didChangeDependencies();
  }
}
